<template>
  <div>
    <Headline :headline1="$t('m.FaceRecognition')+'  /  '" :headline2="$t('m.FaceModeling')" />
    <a-card style="width: 100%">
      <select-tree @checkData="argumentSelect" style="margin-right: 15px" />
      <a-select
        default-value=""
        style="width: 120px; margin-right: 15px"
        @change="handleChange"
      >
        <a-select-option value=""> 全部 </a-select-option>
        <a-select-option value="1"> 已建模 </a-select-option>
        <a-select-option value="0"> 未建模 </a-select-option>
      </a-select>
      <a-input-search
        :placeholder="$t('m.PleaseEnterYourSearchTerms')"
        :enter-button="$t('m.Inquire')"
        v-model="forminitial.key"
        size="default"
        @search="onSearch"
        style="margin-right: 15px; width: 200px"
      />
      <a-checkbox
        @change="checked"
        style="margin-right: 15px"
        :defaultChecked="true"
      >
        {{$t('m.WhetherToDisplayChildNodes')}}
      </a-checkbox>
      <a-dropdown>
        <!-- <a class="ant-dropdown-link" @click="e => e.preventDefault()">
      Hover me <a-icon type="down" />
    </a> -->
        <a-button type="primary" icon="unordered-list">{{$t('m.More')}}</a-button>
        <a-menu slot="overlay">
          <a-menu-item @click="faceCollect" v-if="isTrue('face:modeling:add')">
            <a href="javascript:;">{{$t('m.FaceCollect')}}</a>
          </a-menu-item>
          <a-menu-item
            @click="dabaoUp"
            v-if="isTrue('face:modeling:batchupload')"
          >
            <a href="javascript:;">{{$t('m.PackagingUpload')}}</a>
          </a-menu-item>
          <a-menu-item @click="clearFace" v-if="isTrue('face:modeling:clear')">
            <a href="javascript:;">{{$t('m.ClearFace')}}</a>
          </a-menu-item>
          <a-menu-item
            @click="exportEXcle"
            v-if="isTrue('face:modeling:export')"
          >
            <a href="javascript:;">{{$t('m.ExportExcel')}}</a>
          </a-menu-item>
        </a-menu>
      </a-dropdown>
      <a-table
        style="margin-top: 30px"
        :columns="columns"
        :rowKey="(r, i) => i.toString()"
        :data-source="data"
        :pagination="false"
        :row-selection="{
          onChange: onSelectChangeK,
          selectedRowKeys: selectedRowKeysListK,
        }"
        bordered
      >
      </a-table>
      <a-pagination
        style="margin-top: 20px"
        show-size-changer
        :default-current="1"
        :total="total"
        @change="Pages"
        :pageSizeOptions="['5', '10', '30', '40']"
        @showSizeChange="onShowSizeChange"
        class="pages"
      />
    </a-card>
    <a-modal
      :title="$t('m.UploadFacePhotosInBatches')"
      :visible="visiblesA"
      width="600px"
      @ok="unitOkA"
      @cancel="handleCancelsA"
      :cancelText="$t('m.Cancel')"
    :okText="$t('m.Ok')"
    >
      <a-input style="width: 200px"></a-input>
      <a-upload
        name="file"
        :multiple="false"
        :customRequest="uploadImg"
      >
        <a-button type="primary">{{$t('m.uploadPictures')}}</a-button>
      </a-upload>
      <p style="margin-top:20px;">1. 上传文件必须为压缩的文件，扩展名为.zip；</p>
      <p>
        2.
        批量上传时，每人只能有一张照片，被上传的照片必须以工号命名，不可增加字符。如上传成功并处理完成后不显示照片，请检查命名是否正确；
      </p>
      <p>
        3.
        上传的照片应避免有多人、彩妆、人脸姿态不端正、模糊、照片翻转等难识别现象；
      </p>
    </a-modal>
    <a-modal
      :title="$t('m.FaceCollect')"
      :visible="visiblesB"
      width="600px"
      @ok="unitOkB"
      @cancel="handleCancelsB"
      :cancelText="$t('m.Cancel')"
    :okText="$t('m.Ok')"
    >
    <!-- <input type="file" @change="onchangeFile"/> -->

      <!-- <img v-for="item in imageData" :key="item.id" :src="item.imgpath" alt=""> -->
      <img v-if="fileList.imgpath"
      style="width:102px;height:102px;margin-top:-115px;margin-right:20px;"
       :src="fileList.imgpath" alt="">
       <span key={Math.random()}>
     <a-upload
        @change="handleChangeImg"
        :before-upload="beforeUploadImg"
         name="avatar"
    list-type="picture-card"
    class="avatar-uploader"
     :file-list="imgdataList"
    :customRequest="customRequestimg"
  >
     <div v-if="imgdataList.length < 1">
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">
        Upload
      </div>
    </div>
  </a-upload>
       </span>
  <div>注意：如果存在图片，上传图片会对原有图片进行覆盖，没有请忽略</div>
    </a-modal>
    <Delete ref="clearFace" :dalete="clearData" @confirm="clearIsok" />
  </div>
</template>

<script>
import axios from 'axios'
import Headline from "@/components/Headline";
import Delete from "@/components/Delete";
import SelectTree from "@/components/common/SelectTree";
import {
  getPeopleList,
  exportInfoFace,
  clearFace,
  batchUploadFace,
  uploadFace,
  getModeling
} from "@/api/faceRecognition";
import { Setperms } from "@/assets/js/setperms";
export default {
  name: "FaceModeling",
  components: { Headline, Delete, SelectTree },
  data() {
    return {
      ImgKey:'',
      loading: false,
      imageUrl: '',
      visiblesB:false,
      headers: {
        "Content-Type": "multipart/form-data",
      },
      visiblesA: false,
      clearData: {
        titles: this.$t('m.DeleteThePrompt'),
        type: "exclamation-point",
        text: this.$t('m.AreYouSureToClearFace'),
      },
      data: [],
      columns: [
        {
          title: this.$t('m.jobnumber'),
          dataIndex: "stafforstucode",
        },
        {
          title: this.$t('m.Name'),
          dataIndex: "stafforstuname",
        },
        {
          title: this.$t('m.Sex'),
          dataIndex: "sex",
        },
        {
          title: this.$t('m.CardNumber'),
          dataIndex: "000004143124",
        },
        {
          title: this.$t('m.AffiliatedUnit'),
          dataIndex: "custorgname",
        },

        {
          title: this.$t('m.FaceCollectNumber'),
          dataIndex: "total",
        },
      ],
      forminitial: {
        ymOrgTreeCode: "001",
        infoType: 0,
        viewChild: true,
        isHasModel: "",
        page: 1,
        start: 0,
        limit: 50,
        key: "",
        start: 0,
        page: 1,
        limit: 10,
      },
      total: 0,
      exportnitial: {
        ymOrgTreeCode: "",
        infoType: 0,
        key: "",
        isHasModel: "",
        viewChild: "true",
      },
      selectedRowKeysListK: [],
      selectedList: [],
      imageUrl:'',
      personId:'',
    fileList:{
      imgpath:''
    },
      imgList:[],
      dataList:{
        staffOrStudInfoId:'',
        imagefile:'',
      },
      imgdataList:[]
    };
  },
  created() {
    this.getPersonList();
    this.parms = Setperms(
      this.$route.fullPath,
      JSON.parse(sessionStorage.getItem("menu"))
    );
    console.log(this.parms);
  },
  watch:{
     visible() {
      if (this.visible) {
        this.ImgKey = ''
      } else {
        this.ImgKey = Math.random()
      }
      console.log('this.ImgKey :>> ', this.ImgKey)
    },
  },
  methods: {
    customRequestimg(info){
      console.log(info)
    },
    handleChangeImg(info) {
      console.log(info)
      this.imgdataList = info.fileList;
      this.imageUrl = info.file.type;
      this.imgList = info.fileList
      this.dataList.imagefile = info.file
      // console.log(info)

    },
    beforeUploadImg(info) {
      return false
    },
    unitOkB(){
      if(this.dataList.imagefile == '') return this.$message.warning('请选择上传图片')
      let fileFormData = new FormData();
      fileFormData.append("staffOrStudInfoId", this.dataList.staffOrStudInfoId);
      fileFormData.append("imagefile", this.dataList.imagefile);
      const upload_ax = axios.create({
        baseURL: "/api", //在vite.config.js配置的跨域
        withCredentials: true, //上传请求时是否携带 cookie
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
       upload_ax.post("/Face/Modeling/uploadFace", fileFormData)
       .then((res) => {
         console.log(res.data)
        const msg = res.data.data.msg;
        if (res.data.success == true) {
          this.$message.success(msg);
          this.getPersonList()
          this.visiblesB = false
        } else {
          this.$message.warning(msg);
        }
      })
        .catch(err => {
          this.$message.error('操作失败')
        })
        // this.fileList.imgpath = ''
        setTimeout(() => {
          this.imgdataList = []
        }, 1000);

    },
    handleCancelsB(){
      this.imgdataList = []
      this.visiblesB = false
    },
    faceCollect(){
      if (this.selectedRowKeysListK.length <= 0) {
        return this.$message.warning("请选择人员信息");
      }
      if (this.selectedRowKeysListK.length > 1) {
        return this.$message.warning("只能选择一个人员信息");
      }
      // this.ImgKey = ''
      // console.log(this.personId)
      getModeling({params:{staffOrStudInfoId:this.personId[0].id}})
      .then(res => {
        this.fileList.imgpath = res.data.data[0].imgpath
        console.log(res)
      })
      this.visiblesB = true
    },
    uploadImg(file){
      const config = {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      };
      let fileFormData = new FormData();
      console.log(file);
      fileFormData.append("zipfile", file.file);
      batchUploadFace(fileFormData)
       .then(res => {
         console.log(res)
       })
    },

    onchangeFile(e){
      console.log(e)
    },
    dabaoUp() {
      this.visiblesA = true;
    },
    unitOkA() {},
    handleCancelsA() {
      this.visiblesA = false;
    },
    clearIsok() {
      clearFace({ ids: this.selectedList })
        .then((res) => {
          if (res.data.success == true) {
            this.getPersonList()
            this.fileList.imgpath = ''
            this.$message.success("清除成功");
          }
          if (res.data.success == false) {
            this.$message.warning(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.clearFace.visible = false;
    },
    clearFace() {
      if (this.selectedRowKeysListK.length <= 0) {
        return this.$message.warning("请选择人员信息");
      }
      this.$refs.clearFace.visible = true;
    },
    onSelectChangeK(a,e) {
      this.selectedRowKeysListK = a;
      let list = []
      this.personId = e
      e.forEach(item => {
        list.push(item.id)
      })
      this.selectedList = list.join(',')
      console.log(e);
      this.dataList.staffOrStudInfoId = e[0].id
    },
    exportEXcle() {
      exportInfoFace(this.exportnitial)
        .then((res) => {
          if (res.data.success == true) {
            location.href = this.$store.state.BaseUrl  + res.data.msg;
          // console.log(res.data.msg)
          }
          if (res.data.success == false) {
            this.$message.error(res.data.msg);
          }
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    isTrue(str) {
      return this.parms.indexOf(str) !== -1;
    },
    handleChange(value) {
      this.forminitial.isHasModel = value;
      this.exportnitial.isHasModel = value;
      this.getPersonList();
      console.log(value);
    },
    checked(e) {
      console.log(e.target.checked);
      this.forminitial.viewChild = e.target.checked;
      this.exportnitial.viewChild = e.target.checked;
      this.getPersonList();
    },
    argumentSelect(data) {
      this.forminitial.ymOrgTreeCode = data.ymorgtreecode;
      this.exportnitial.ymOrgTreeCode = data.ymorgtreecode;
      this.getPersonList();
      console.log(data.ymorgtreecode);
    },
    onSearch() {
      this.getPersonList();
    },
    getPersonList() {
      getPeopleList({ params: this.forminitial })
        .then((res) => {
          this.total = res.data.total;
          res.data.data.forEach((item) => {
            if (item.sex == 1) {
              item.sex = "男";
            }
            if (item.sex == 2) {
              item.sex = "女";
            }
          });
          this.data = res.data.data;
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onShowSizeChange(page, limit) {
      this.forminitial.page = page;
      this.forminitial.limit = limit;
      this.getPersonList();
    },
    Pages(page, pageSize) {
      this.forminitial.limit = pageSize;
      this.forminitial.page = page;
      this.forminitial.start = (page - 1) * pageSize;
      this.getPersonList();
    },
  },
};
</script>

<style lang="scss" scoped>

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
/deep/ .ant-upload-picture-card-wrapper {
  width: 0 !important;
}
</style>
